package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.QueryObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//角色控制器
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //查询    /role/list.do
    @RequestMapping("/list")
    public String list(Model model , @ModelAttribute("qo")QueryObject qo){
        PageInfo<Role> pageResult = roleService.query(qo);
        model.addAttribute("pageResult",pageResult);
        return "role/list";
    }
    //删除    /role/delete.do?id=?
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        if (id != null) {
            roleService.deleteById(id);
        }
        return new JsonResult();
    }
    //修改或者新增
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role , Long[] ids){
        if (role.getId() != null) {
            roleService.update(role , ids);
        }else {
            roleService.insert(role , ids);
        }
        return "redirect:/role/list.do";
    }
    //跳转新增和修改页面    /role/input.do
    @RequestMapping("/input")
    public String input(Model model,Long id){
        // 查询所有权限给浏览器
        model.addAttribute("permissions", permissionService.listAll());
        //如果请求里有id则是修改操作根据id查询该条数据共享给编辑页面
        if (id != null) {
            model.addAttribute("role",roleService.selectById(id));
        }
        return "role/input";
    }
}
